package cn.jiyun.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> map = request.getQueryParams();
        List<String> list = map.get("token");
        //判断是否传递了请求参数
        if(CollectionUtils.isEmpty(list)){
            //说明没有传递token参数，没有权限继续访问
            ServerHttpResponse response = exchange.getResponse();
            // 返回响应码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //完成响应
            return response.setComplete();
        }
        //放行过滤器
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
